﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using APA_DAO;
using TAM_SPORT;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using DAO;

namespace AMS
{
    public partial class FrmThuTienPhong : Form
    {
        private int pid = -1;
        public FrmThuTienPhong()
        {
            InitializeComponent();
        }
        private int soThuePhong = 0;
        public FrmThuTienPhong(int soThuePhong)
        {
            InitializeComponent();
            this.soThuePhong = soThuePhong;
            txtSoThuePhong.Text = soThuePhong.ToString();
            load(soThuePhong);
            txtNgayThu.Text = DateTime.Now.ToString("dd/MM/yyyy");
            loadPrint(soThuePhong);
            this.BackColor = Color.LightCyan;
        }

        private bool validate()
        {
            float before = 0;
            float after = 0;
            bool errFlg = false;
            StringBuilder str = new StringBuilder();
            int i = 0;

            if (string.IsNullOrEmpty(txtChiSoDienSau.Text))
            {
                i++;
                str.Append(i + ". Bạn chưa nhập chỉ số điện sau");
                errFlg = true;
            }
            else
            {
                if (!float.TryParse(txtChiSoDienSau.Text, out after))
                {
                    i++;
                    str.Append(i + ". Chỉ số điện sau phải là số");
                    errFlg = true;
                }
            }

            if (!float.TryParse(txtChiSoDienTruoc.Text, out before))
            {
                i++;
                if (errFlg)
                {
                    str.Append("\n");
                }
                str.Append(i + ". Chỉ số điện trước phải là số.");
                errFlg = true;
            }

            if (after < before)
            {
                i++;
                if (errFlg)
                {
                    str.Append("\n");
                }
                str.Append(i + ". Chỉ số điện sau phải lớn hơn hoặc bằng chỉ số điện trước.");
                errFlg = true;
            }

            if (!float.TryParse(txtChiSoNuocTruoc.Text, out before))
            {
                i++;
                if (errFlg)
                {
                    str.Append("\n");
                }
                str.Append(i + ". Chỉ số nước trước phải là số.");
                errFlg = true;
            }

            if (string.IsNullOrEmpty(txtChiSoNuocSau.Text))
            {
                i++;
                if (errFlg)
                {
                    str.Append("\n");
                }
                str.Append(i + ". Chưa nhập chỉ số nước sau.");
                errFlg = true;
            }
            else
            {
                if (!float.TryParse(txtChiSoNuocSau.Text, out after))
                {
                    i++;
                    if (errFlg)
                    {
                        str.Append("\n");
                    }
                    str.Append(i + ". Chỉ số nước sau phải là số.");
                    errFlg = true;
                }
            }

            if (after < before)
            {
                i++;
                if (errFlg)
                {
                    str.Append("\n");
                }
                str.Append(i + ". Chỉ số nước sau phải lớn hơn hoặc bằng chỉ số nước trước.");
                errFlg = true;
            }

            if (string.IsNullOrEmpty(txtRoomPrice.Text))
            {
                i++;
                if (errFlg)
                {
                    str.Append("\n");
                }
                str.Append(i + ". Bạn phải nhập đơn giá phòng.");
                errFlg = true;
            }
            else
            {
                if (!float.TryParse(txtRoomPrice.Text, out after))
                {
                    i++;
                    if (errFlg)
                    {
                        str.Append("\n");
                    }
                    str.Append(i + ". Đơn giá phòng phải là số.");
                    errFlg = true;
                }
            }

            if (string.IsNullOrEmpty(txtNgayThu.Text))
            {
                i++;
                if (errFlg)
                {
                    str.Append("\n");
                }
                str.Append(i + ". Chưa nhập ngày thu tiền.");
                errFlg = true;
            }
            else
            {
                i++;
                DateTime day;
                if (!DateTime.TryParseExact(txtNgayThu.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out day))
                {
                    if (errFlg)
                    {
                        str.Append("\n");
                    }
                    str.Append(i.ToString() + ". Ngày thu sai định dạng.");
                    errFlg = true;
                }
            }

            if (!string.IsNullOrEmpty(txtOtherPrice.Text) &&
                !float.TryParse(txtOtherPrice.Text, out after))
            {
                i++;
                if (errFlg)
                {
                    str.Append("\n");
                }
                str.Append(i + ". Chi phí khác phải là số.");
                errFlg = true;
            }

            if (!string.IsNullOrEmpty(txtCustPay.Text) &&
                !float.TryParse(txtCustPay.Text, out after))
            {
                i++;
                if (errFlg)
                {
                    str.Append("\n");
                }
                str.Append(i + ". Số tiền khách trả phải là số.");
                errFlg = true;
            }

            if (!string.IsNullOrEmpty(str.ToString()))
            {
                Error er = new Error(str.ToString());
                er.ShowDialog();
                er.Dispose();
            }
            return !errFlg;
        }


        private void loadPrint( int id)
        {
            ThuePhongDao dao = new ThuePhongDao();
            DataRow row = dao.getPrint(id);
            if(row != null)
            {
                txtChiSoDienTruoc.Text = float.Parse(row["CHI_SO_DIEN_TRUOC"].ToString()).ToString("#,##0.##");
                txtChiSoDienSau.Text = float.Parse(row["CHI_SO_DIEN_SAU"].ToString()).ToString("#,##0.##");
                txtTieuthuDien.Text = float.Parse(row["TIEU_THU_DIEN"].ToString()).ToString("#,##0.##");
                txtChiSoNuocTruoc.Text = float.Parse(row["CHI_SO_NUOC_TRUOC"].ToString()).ToString("#,##0.##");
                txtChiSoNuocSau.Text = float.Parse(row["CHI_SO_NUOC_SAU"].ToString()).ToString("#,##0.##");
                txtTieuThuNuoc.Text = float.Parse(row["TIEU_THU_NUOC"].ToString()).ToString("#,##0.##");
            }
            this.BackColor = Color.LightCyan;
        }
        private bool printFlg = false;
        public FrmThuTienPhong(int soThuePhong, bool printFlg )
        {
            InitializeComponent();
            this.soThuePhong = soThuePhong;
            txtSoThuePhong.Text = soThuePhong.ToString();
            load(soThuePhong);
            txtNgayThu.Text = DateTime.Now.ToString("dd/MM/yyyy");
            btnSave.Text = "In";
            this.printFlg = printFlg;
            lblKhachTra.Visible = false;
            lblTienThoi.Visible = false;
            txtCustPay.Visible = false;
            txtRefund.Visible = false;
            this.BackColor = Color.LightCyan;
        }

        private void load(int id)
        {
            ThuePhongDao dao = new ThuePhongDao();
            DataRow tp = dao.getThuePhong(id);
            if (tp != null)
            {
                txtRoomNumber.Text = tp["SO_PHONG"].ToString();
                txtChiSoNuocTruoc.Text = float.Parse(tp["CHI_SO_NUOC"].ToString()).ToString("#,##0.##");
                txtChiSoDienTruoc.Text = float.Parse(tp["CHI_SO_DIEN"].ToString()).ToString("#,##0.##");

                txtCustomerName.Text = tp["HO_VA_TEN"].ToString();
                txtNgayKetThuc.Text = DateTime.Parse(tp["NGAY_KET_THUC"].ToString()).ToString("dd/MM/yyyy");
                txtNetDay.Text = DateTime.Parse(tp["NGAY_KET_THUC"].ToString()).AddMonths((int)nbnMonth.Value).ToString("dd/MM/yyyy");
            }
            tp = dao.getPrice(id);
            if (tp != null)
            {
                txtElecPrice.Text = float.Parse(tp["ELE_PRICE"].ToString()).ToString("#,##0.##");
                txtWaterPrice.Text = float.Parse(tp["WAT_PRICE"].ToString()).ToString("#,##0.##");
                txtRoomPrice.Text = float.Parse(tp["ROOM_PRICE"].ToString()).ToString("#,##0.##");
                txtOtherPrice.Text = float.Parse(tp["OTHER_COST"].ToString()).ToString("#,##0.##");
                txtRoomCost.Text = float.Parse(tp["ROOM_PRICE"].ToString()).ToString("#,##0.##");
                txtMotoNum.Text = float.Parse(tp["MOTO_COUNT"].ToString()).ToString("#,##0.##");
                txtMotoPrice.Text = float.Parse(tp["MOTO_PRICE"].ToString()).ToString("#,##0.##");
                txtTotalOfMoto.Text = (float.Parse(tp["MOTO_COUNT"].ToString()) * float.Parse(tp["MOTO_PRICE"].ToString())).ToString("#,##0.##");
                txtEleCost.Text = "0";
                txtWatCost.Text = "0";
                float motoFee = string.IsNullOrEmpty(txtTotalOfMoto.Text) ? 0 : float.Parse(txtTotalOfMoto.Text.Replace(",", ""));

                txtTotal.Text = (motoFee + float.Parse(tp["ROOM_PRICE"].ToString()) + float.Parse(tp["OTHER_COST"].ToString())).ToString("#,##0.##");
            }

            
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void FrmThuTienPhong_Load(object sender, EventArgs e)
        {

        }

        private String RemoveComma(String value)
        {
            if (value != null && value.Contains(","))
            {
                value = value.Replace(",", String.Empty).Trim();
            }
            return value;
        }
        private void txtChiSoDienSau_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtChiSoDienSau.Text))
            {
                float end = float.Parse(RemoveComma(txtChiSoDienSau.Text));
                float start = float.Parse(RemoveComma(txtChiSoDienTruoc.Text));
                txtTieuthuDien.Text = (end - start).ToString("#,##0.##");
                count();
            }
            else
            {
                txtTieuthuDien.Text = "0";
            }
            if (RemoveComma(txtChiSoDienSau.Text).Length > 3)
            {
                txtChiSoDienSau.Text = decimal.Parse(RemoveComma(txtChiSoDienSau.Text)).ToString("#,##0.##");
                txtChiSoDienSau.Select(txtChiSoDienSau.Text.Length, 0);
            }
        }

        private void txtChiSoDienSau_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtChiSoNuocSau_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtChiSoNuocSau_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtChiSoNuocSau.Text))
            {
                float end = float.Parse(RemoveComma(txtChiSoNuocSau.Text));
                float start = float.Parse(RemoveComma(txtChiSoNuocTruoc.Text));
                txtTieuThuNuoc.Text = (end - start).ToString("#,##0.##");
                count();
            }
            if (RemoveComma(txtChiSoNuocSau.Text).Length > 3)
            {
                txtChiSoNuocSau.Text = decimal.Parse(RemoveComma(txtChiSoNuocSau.Text)).ToString("#,##0.##");
                txtChiSoNuocSau.Select(txtChiSoNuocSau.Text.Length, 0);
            }
            
        }

        private void dtpNgayThu_ValueChanged(object sender, EventArgs e)
        {
            txtNgayThu.Text = dtpNgayThu.Value.ToString("dd/MM/yyyy");
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            DateTime day;
            if (DateTime.TryParseExact(txtNgayKetThuc.Text.ToString(), "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out day))
            {
                txtNetDay.Text = day.AddMonths((int)nbnMonth.Value).ToString("dd/MM/yyyy");
            }
            count();
        }

        private void count()
        {
            float roomPrice = float.Parse(txtRoomPrice.Text.Replace(",", ""));
            float roomCost = (float)nbnMonth.Value * roomPrice;
            float elecPrice = float.Parse(txtElecPrice.Text.Replace(",", ""));
            float elecUsed = string.IsNullOrEmpty(txtTieuthuDien.Text)? 0 : float.Parse(txtTieuthuDien.Text.Replace(",", ""));
            float elecCost = elecPrice * elecUsed;
            float watPrice = float.Parse(txtWaterPrice.Text.Replace(",", ""));
            float watUsed = string.IsNullOrEmpty(txtTieuThuNuoc.Text) ? 0 : float.Parse(txtTieuThuNuoc.Text.Replace(",", ""));
            float watCost = watPrice * watUsed;
            float otherCost = string.IsNullOrEmpty(txtOtherPrice.Text) ? 0 : float.Parse(txtOtherPrice.Text.Replace(",", ""));
            txtRoomCost.Text = ((float)nbnMonth.Value * roomPrice).ToString("#,##0.##");
            txtEleCost.Text = elecCost.ToString("#,##0.##");
            txtWatCost.Text = watCost.ToString("#,##0.##");
            float motoFee = string.IsNullOrEmpty(txtTotalOfMoto.Text)? 0 : float.Parse(txtTotalOfMoto.Text.Replace(",", ""));
            txtTotal.Text = (roomCost + elecCost + watCost + otherCost + motoFee).ToString("#,##0.##");           


            if (!string.IsNullOrEmpty(txtCustPay.Text))
            {
                float total = string.IsNullOrEmpty(txtTotal.Text) ? 0 : float.Parse(txtTotal.Text.Replace(",", ""));
                float cusPay = string.IsNullOrEmpty(txtCustPay.Text) ? 0 : float.Parse(txtCustPay.Text.Replace(",", ""));
                if (cusPay > total)
                {
                    txtRefund.Text = (cusPay - total).ToString("#,##0.##");
                }
                else
                {
                    txtRefund.Text = "0";
                }
            }

        }

        private void txtOtherPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtOtherPrice_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtOtherPrice.Text))
            {
                count();
            }
            if (RemoveComma(txtOtherPrice.Text).Length > 3)
            {
                txtOtherPrice.Text = decimal.Parse(RemoveComma(txtOtherPrice.Text)).ToString("#,##0.##");
                txtOtherPrice.Select(txtOtherPrice.Text.Length, 0);
            }
        }

        private void txtCustPay_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtCustPay_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtCustPay.Text))
            {
                float total = string.IsNullOrEmpty(txtTotal.Text) ? 0 : float.Parse(txtTotal.Text.Replace(",", ""));
                float cusPay = string.IsNullOrEmpty(txtCustPay.Text) ? 0 : float.Parse(txtCustPay.Text.Replace(",", ""));
                if (cusPay > total)
                {
                    txtRefund.Text = (cusPay - total).ToString("#,##0.##");
                }
                else
                {
                    txtRefund.Text = "0";
                }
            }
            if (RemoveComma(txtCustPay.Text).Length > 3)
            {
                txtCustPay.Text = decimal.Parse(RemoveComma(txtCustPay.Text)).ToString("#,##0.##");
                txtCustPay.Select(txtCustPay.Text.Length, 0);
            }
        }


        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int GetWindowThreadProcessId(HandleRef handle, out int processId);

        private void releaseObject(Object ob)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(ob);
                ob = null;
            }
            catch (Exception ex)
            {
                ob = null;
                Console.WriteLine(ex.ToString());
            }
            GC.Collect();
        }

        private void KillProcess(int pid, string processName)
        {
            // to kill current process of excel
            System.Diagnostics.Process[] AllProcesses = System.Diagnostics.Process.GetProcessesByName(processName);
            foreach (System.Diagnostics.Process process in AllProcesses)
            {
                if (process.Id == pid)
                {
                    process.Kill();
                }
            }
            AllProcesses = null;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (validate())
            {
                float roomPrice = float.Parse(txtRoomPrice.Text.Replace(",", ""));
                float roomCost = (float)nbnMonth.Value * roomPrice;

                float elecPrice = float.Parse(txtElecPrice.Text.Replace(",", ""));
                float elecBefore = string.IsNullOrEmpty(txtChiSoDienTruoc.Text) ? 0 : float.Parse(txtChiSoDienTruoc.Text.Replace(",", ""));
                float elecAfter = string.IsNullOrEmpty(txtChiSoDienSau.Text) ? 0 : float.Parse(txtChiSoDienSau.Text.Replace(",", ""));

                float watPrice = float.Parse(txtWaterPrice.Text.Replace(",", ""));
                float watBefore = string.IsNullOrEmpty(txtChiSoNuocTruoc.Text) ? 0 : float.Parse(txtChiSoNuocTruoc.Text.Replace(",", ""));
                float watAfter = string.IsNullOrEmpty(txtChiSoNuocSau.Text) ? 0 : float.Parse(txtChiSoNuocSau.Text.Replace(",", ""));


                float otherCost = string.IsNullOrEmpty(txtOtherPrice.Text) ? 0 : float.Parse(txtOtherPrice.Text.Replace(",", ""));

                float tienPhong = string.IsNullOrEmpty(txtRoomCost.Text) ? 0 : float.Parse(txtRoomCost.Text.Replace(",", ""));
                float motoFee = string.IsNullOrEmpty(txtTotalOfMoto.Text) ? 0 : float.Parse(txtTotalOfMoto.Text.Replace(",", ""));
                DateTime day;
                if (!DateTime.TryParseExact(txtNgayKetThuc.Text.ToString(), "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out day))
                {
                    Error er = new Error("Định dạng ngày tháng chưa đúng. Vui lòng xem lại cái mục ngày tháng");
                    er.ShowDialog();
                    er.Dispose();
                }

                DateTime collectDay;
                if (!DateTime.TryParseExact(txtNgayThu.Text.ToString(), "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out collectDay))
                {
                    Error er = new Error("Ngày thu sai định dạng Ngày/Tháng/Năm");
                    er.ShowDialog();
                    er.Dispose();
                }
                ThuePhongDao dao = new ThuePhongDao();
                if (!printFlg)
                {
                    if (dao.thueTien(this.soThuePhong, collectDay,
                        watBefore, watAfter, elecBefore, elecAfter, tienPhong, (float)nbnMonth.Value, otherCost,
                        day, elecPrice, watPrice, motoFee))
                    {
                        Result re = new Result("Thu tiền thành công.");
                        re.ShowDialog();
                        re.Dispose();
                        this.Close();
                    }
                    else
                    {
                        Error er = new Error("Thu tiền thất bại.");
                        er.ShowDialog();
                        er.Dispose();
                    }
                }
                else
                {
                    if (dao.print(this.soThuePhong, collectDay,
                        watBefore, watAfter, elecBefore, elecAfter, tienPhong, (float)nbnMonth.Value, otherCost,
                        day, elecPrice, watPrice, motoFee))
                    {
                        try
                        {
                            Excel.Application application = new Excel.Application();
                            Excel.Workbook workbook = null;
                            workbook = application.Workbooks.Open(System.AppDomain.CurrentDomain.BaseDirectory + @"Resources\Inform.xlsx");

                            HandleRef hwnd = new HandleRef(application, (IntPtr)application.Hwnd);
                            GetWindowThreadProcessId(hwnd, out pid);

                            Excel.Worksheet worksheet = workbook.Sheets[1];
                            try
                            {
                                worksheet.Cells[4, 5] = txtRoomNumber.Text;
                                worksheet.Cells[5, 5] = txtCustomerName.Text;
                                worksheet.Cells[6, 5] = DateTime.Now.ToString("MM/yyyy");
                                worksheet.Cells[8, 4] = tienPhong.ToString("#,###.##");
                                float electCost = ((elecAfter - elecBefore) * elecPrice);
                                worksheet.Cells[9, 4] = electCost.ToString("#,###.##");
                                float waterCost = ((watAfter - watBefore) * watPrice);
                                worksheet.Cells[10, 4] = waterCost.ToString("#,###.##");
                                worksheet.Cells[11, 4] = otherCost.ToString("#,###.##");

                                worksheet.Cells[13, 4] = (otherCost + roomCost + waterCost + electCost).ToString("#,###.##");


                                workbook.PrintOutEx(Type.Missing,
                                            Type.Missing,
                                            1,
                                            false,
                                            SqlHelper.readConfigFile("Printer"),
                                            false,
                                            true,
                                            Type.Missing, false);

                                /* Preview 
                                application.Visible = true;
                                workbook.PrintOutEx(Type.Missing,
                                                    Type.Missing,
                                                    1,
                                                    true,
                                                    SqlHelper.readConfigFile("Printer"),
                                                    false,
                                                    true,
                                                    Type.Missing, false);*/
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.ToString());
                            }
                            finally
                            {
                                application.DisplayAlerts = false;
                                workbook.Close();
                                application.DisplayAlerts = true;
                                application.Quit();
                                releaseObject(application);
                                releaseObject(workbook);
                                releaseObject(worksheet);
                                KillProcess(pid, "EXCEL");
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
                        this.Close();
                    }
                    else
                    {
                        Error er = new Error("Lỗi. Không lưu được trước khi in.");
                        er.ShowDialog();
                        er.Dispose();
                    }
                }
            }
        }
    }
}
